
<template>
  <div class="login-bg">
    <div class="login-container">
      <div class="login-header">
        <img class="logo mr10" src="../../assets/img/logo.svg" alt="" />
        <div class="login-title">家校通管理系统</div>
      </div>

      <!-- 新增的按钮 -->
      <div class="button-group-container">
        <el-button-group>
          <el-button
              :class="{ active: param.role === 'admin' }"
              @click="switchRole('admin')"
          >
            <img src="../../assets/img/admin.png" class="button-icon" />
            管理员
          </el-button>
          <el-button
              :class="{ active: param.role === 'teacher' }"
              @click="switchRole('teacher')"
          >
            <img src="../../assets/img/teacher.png" class="button-icon" />
            老师
          </el-button>
        </el-button-group>
      </div>

      <el-form :model="param" :rules="rules" ref="loginForm" size="large">
        <el-form-item prop="username">
          <el-input v-model="param.username" placeholder="用户名">
            <template #prepend>
              <el-icon>
                <User />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
              type="password"
              placeholder="密码"
              v-model="param.password"
              @keyup.enter="submitForm"
          >
            <template #prepend>
              <el-icon>
                <Lock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-button
            class="login-btn"
            type="primary"
            size="large"
            @click="submitForm"
        >
          登录
        </el-button>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { useTabsStore } from '@/store/tabs';
import { usePermissStore } from '@/store/permiss';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import axios from 'axios';
import {tryLogin} from "@/api/forIdentify";

interface LoginInfo {
  username: string;
  password: string;
  role: string;
}

const lgStr = localStorage.getItem('login-param');
const defParam = lgStr ? JSON.parse(lgStr) : null;
const checked = ref(lgStr ? true : false);

const router = useRouter();
const param = reactive<LoginInfo>({
  username: defParam ? defParam.username : '',
  password: '',
  role: defParam ? defParam.role : 'admin', // 默认 admin
});

const rules: FormRules = {
  username: [
    {
      required: true,
      message: '请输入用户名',
      trigger: 'blur',
    },
  ],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
};

const permiss = usePermissStore();
const loginForm = ref<FormInstance>();


// 定义角色切换方法
const switchRole = (role: string) => {
  param.role = role; // 更新当前角色
  localStorage.setItem('vuems_role', role); // 更新 localStorage 中的角色信息
};

// 登录逻辑
const submitForm = async () => {
  if (!loginForm.value) return;
  loginForm.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 向后端发送请求
        const response = await tryLogin({
          username: param.username,
          password: param.password,
          role: param.role,
        })

        // 检查后端返回的 token 是否存在
        if (response.data.token) {
          ElMessage.success('登录成功');
          localStorage.setItem('token', response.data.token); // 更新令牌
          localStorage.setItem('vuems_name', param.username); // 设置用户的登录状态
          localStorage.setItem('vuems_role', param.role); // 存储角色信息

          // 如果后端返回了角色信息，更新角色信息
          if (response.data.role) {
            const backendRole = response.data.role;
            const roleFromBackend = backendRole || 'admin'; // 默认为 admin
            localStorage.setItem('vuems_role', roleFromBackend); // 更新 localStorage 中的角色信息
            param.role = roleFromBackend; // 更新当前角色
          }

          // 根据角色更新权限列表
          permiss.updatePermissionsBasedOnRole(param.role); // 动态更新权限列表

          router.push('/dashboard'); // 跳转到首页
        }
        else {
          ElMessage.error(response.message);
        }
      } catch (error) {
        // 错误处理逻辑
        if (error.response && error.response.status === 401) {
          ElMessage.error('用户名或密码错误'); // 401 错误提示
        } else if (error.response && error.response.status === 400) {
          ElMessage.error(error.response.message || '登录失败，请求无效'); // 400 错误提示
        } else if (error.response && error.response.status === 500) {
          ElMessage.error('登录失败，服务器内部错误'); // 500 错误提示
        } else {
          ElMessage.error('登录失败，请检查网络或联系管理员'); // 其他错误提示
        }
        console.error('登录请求失败:', error);
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入内容'); // 表单验证失败提示
    }
  });
};

const tabs = useTabsStore();
tabs.clearTabs();
</script>

<style scoped>
.login-bg {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100vh;
  background: url(../../assets/img/login_bg.jpg) center/cover no-repeat;
}

.login-header {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 40px;
}

.logo {
  width: 35px;
}

.login-title {
  font-size: 22px;
  color: #333;
  font-weight: bold;
}

.login-container {
  width: 450px;
  border-radius: 5px;
  background: #fff;
  padding: 40px 50px 50px;
  box-sizing: border-box;
}

.pwd-tips {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  margin: -10px 0 10px;
  color: #787878;
}

.pwd-checkbox {
  height: auto;
}

.login-btn {
  display: block;
  width: 100%;
}

.login-tips {
  font-size: 12px;
  color: #999;
}

.login-text {
  display: flex;
  align-items: center;
  margin-top: 20px;
  font-size: 14px;
  color: #787878;
}

/* 新增样式 */
.button-group-container {
  text-align: center;
  margin-bottom: 20px; /* 根据需要调整间距 */
}

/* 按钮激活状态的样式 */
.active {
  background-color: rgb(197.7, 225.9, 255); /* 浅蓝色 */
  border-color: rgb(197.7, 225.9, 255); /* 浅蓝色 */
}

/* 调整图标和文字的间距 */
.button-icon {
  width: 24px;
  height: 24px;
  margin-right: 8px;
}
</style>
